<template>
    <div class="category">
        <van-sidebar v-model="active" @change="handleChooseCategory">
            <van-sidebar-item v-for="category in categories" :key="category.id" :title="category.name" />
        </van-sidebar>

        <!-- 右侧显示分类下的品牌 -->
        <div class="right-box">
            <van-empty v-if="brands.length === 0"
                image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" image-size="80"
                description="该分类下暂无品牌" />
            <van-grid v-else>
                <van-grid-item v-for="brandItem in brands" :icon="brandItem.imageUrl" :text="brandItem.title" :key="brandItem.id" :to="{
                    path: '/list',
                    query: {
                        id:brandItem.id
                    },
                }" />
            </van-grid>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { getCategories, getBrandsByCategory } from '@/api/category'


// 左侧边栏中选中项的索引
const active = ref(3)

// 分类
const categories = ref<any>([])

// 品牌
const brands = ref<any>([])

/**
 * 查询所有分类数据
 */
const fetchCategoriesData = async () => {
    try {
        // 查询分类
        const res: any = await getCategories()
        console.log('分类:', res)
        // categories.value = res.map(category => category.trim())
        categories.value = res.list
        // 默认将激活分类下的品牌也查询出来
        handleChooseCategory(active.value)
    } catch (error) {
        console.log('查询分类异常:', error)
    }
}
fetchCategoriesData()


/**
 * 处理选择分类操作
 */
const handleChooseCategory = async (index: number) => {
    console.log('索引：', index);
    try {
        // 根据分类查询品牌
        const res: any = await getBrandsByCategory(categories.value[index].id)
        console.log('品牌：', res);
        brands.value = res.categories
        console.log('brands:', res.categories);

    } catch (error) {
        console.log('查询品牌异常：', error);
    }
}
</script>

<style lang="less" scoped>
.category {
    display: flex;

    .right-box {
        flex: 1;
    }
}
.van-sidebar-item--select, .van-sidebar-item--select:visited{
    background-color: orangered;
    color: white;
}
.van-grid-item {
    background-color: orangered;
}

</style>
